package com.example.arithmeticleetcode.learnArithmetic2.dynamic_programming;

/**
 * @program: arithmetic-leetcode
 * @description: 连续子数组的最大和
 * @author: FangZhen
 * @create: 2020-12-18 11:07
 **/
public class MaxSubArray {
    public static void main(String[] args) {
        int[] nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
        System.out.println(maxSubArray(nums));
        System.out.println(maxSubArray2(nums));
        System.out.println(maxSubArray2(new int[]{-1}));
    }

    /**
     * 时间复杂度O(N) 空间复杂度O(1)
     * @param nums
     * @return
     */
    public static int maxSubArray2(int[] nums) {
        if (nums == null || nums.length == 0) return 0;
        int dp = nums[0];
        int max = dp;
        for (int i = 1; i < nums.length; i++) {
            if (dp <= 0) {
                dp = nums[i];
            } else {
                dp = dp + nums[i];
            }
            max = Math.max(dp, max);
        }
        return max;
    }

    /**
     * 时间复杂度 O(N) 空间复杂度O(N)
     *
     * @param nums {-2, 1, -3, 4, -1, 2, 1, -5, 4}
     * @return
     */
    public static int maxSubArray(int[] nums) {
        if (nums == null || nums.length == 1) return 0;
        int[] dp = new int[nums.length];
        dp[0] = nums[0];
        int max = dp[0];
        for (int i = 1; i < nums.length; i++) {
            int prev = dp[i - 1];
            if (prev <= 0) {
                dp[i] = nums[i];
            } else {
                dp[i] = prev + nums[i];
            }
            max = Math.max(dp[i], max);
        }
        return max;
    }
}
